package top.yokey.shopai.zcom.voice;

import android.media.MediaRecorder;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressWarnings("ALL")
public class VoiceHelp {

    private static volatile VoiceHelp instance = null;
    private String filePath = "";
    private String direction = "";
    private boolean isPrepared = false;
    private MediaRecorder mediaRecorder = null;
    private StateListener stateListener = null;

    public static VoiceHelp get() {

        if (instance == null) {
            synchronized (VoiceHelp.class) {
                if (instance == null) {
                    instance = new VoiceHelp();
                }
            }
        }
        return instance;

    }

    public void init(String direction) {

        this.direction = direction;

    }

    public void prepare() {

        try {
            isPrepared = false;
            File dir = new File(direction);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String fileName = UUID.randomUUID().toString() + ".amr";
            File file = new File(dir, fileName);
            filePath = file.getAbsolutePath();
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOutputFile(file.getAbsolutePath());
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediaRecorder.prepare();
            mediaRecorder.start();
            isPrepared = true;
            if (stateListener != null) {
                stateListener.prepared();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void release() {

        try {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void cancel() {

        release();
        if (filePath != null) {
            File file = new File(filePath);
            file.delete();
            filePath = null;
        }

    }

    public String getFilePath() {

        return filePath;

    }

    public int getLevel(int level) {

        if (isPrepared) {
            try {
                return level * mediaRecorder.getMaxAmplitude() / 32768 + 1;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 1;

    }

    public void setOnStateListener(StateListener stateListener) {

        this.stateListener = stateListener;

    }

    public interface StateListener {

        void prepared();

    }

}
